//
//  OAtuhViewController.swift
//  艾小夕の微小博
//
//  Created by 艾小新 on 15/10/17.
//  Copyright © 2015年 艾小新. All rights reserved.
//

import UIKit
import SVProgressHUD

class OAtuhViewController: UIViewController,UIWebViewDelegate {

    override func viewDidLoad() {
        super.viewDidLoad()
        title = "新浪微博登陆"
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "取消", style: UIBarButtonItemStyle.Plain, target: self, action: "close")
        
    }
     func close() {
        
        dismissViewControllerAnimated(true, completion: nil)
    }
    
    override func loadView() {
        super.loadView()
        
        
        let web = UIWebView()
        
        view = web
        
        web.delegate = self
        
        
        // 通过单例拿到最初始的URL
        let url =  NetworkTools.sharedTools.oauthURL()
        
        web.loadRequest(NSURLRequest(URL: url))
        
        
        
        
    }
    
    /// MARK: WebView代理方法
    
    func webViewDidStartLoad(webView: UIWebView) {
        
        print("start")
        
    }
    
    func webViewDidFinishLoad(webView: UIWebView) {
        
        print("end")
    }
    
    // 重定向
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        
        
        let urlString = request.URL!.absoluteString
        // 判断是否包含回调地址
        if !urlString.hasPrefix(NetworkTools.sharedTools.redirectUri) {
            return true
        }
        
        print("判断参数")
        print(request.URL?.query)
        if let query = request.URL?.query where query.hasPrefix("code=") {
            print("获取授权码")
            // 从 query 中截取授权码
            let code = (query as NSString).substringFromIndex(5)
            print(code)
            loadAccessToken(code)
        } else {
            close()
        }
        
        return false

    }
    
    private func loadAccessToken(code: String) {
        NetworkTools.sharedTools.loadAccessToken(code) { (result, error) -> () in
            if error != nil || result == nil {
                SVProgressHUD.showInfoWithStatus("你的呢网络不给力")
                
                // 延时一段时间再关闭
                let when = dispatch_time(DISPATCH_TIME_NOW, Int64(1 * NSEC_PER_SEC))
                dispatch_after(when, dispatch_get_main_queue()) {
                    self.close()
                }
                
                return
            }
            
            // 字典转模型
            let account = UserAccount(dict: result!)

            // TODO: 用户登录成功后，加载当前用户的个人信息
            print(account)
        }
    }
    


}
